package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
    /**
     * @Date: 2020/8/3
     * @Param: file
     * @return: result
     * @NewDescription: 文件上传
     **/
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        String path = "";
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取内容
            byte[] context = file.getBytes();
            //获取扩展名
            String ext = "";
            if (!StringUtils.isEmpty(file)) {
                int i = filename.lastIndexOf(".");
                ext = filename.substring(i + 1);
            }
            FastDFSFile fastDFSFile = new FastDFSFile(filename, context, ext);
            String[] uploadResults = FastDFSClient.upload(fastDFSFile);
            //获取组名
            String groupName = uploadResults[0];
            //获取文件存储路径
            String remoteFileName = uploadResults[1];
            //完整路径
             path = FastDFSClient.getTrackerUrl() + groupName + "/" + remoteFileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(true, StatusCode.OK, "上传成功",path);
    }
}
